# ndarry缺失值填充均值

import numpy as np

# 填充每一列的均值
def fill_nan(t1):
    # 选取列
    for i in range(t1.shape[1]):
        temp_col = t1[:,i] # 当前的一列
        nan_num = np.count_nonzero(temp_col!= temp_col)

        if nan_num != 0:  # 如果不为o,说明当前这一列有nan
            # 当前一列不为nan的array
            temp_not_nan_col = temp_col[temp_col==temp_col]
            # 选中当前nan 的位置,把值赋值为不为nan的均值
            temp_col[np.isnan(temp_col)] = temp_not_nan_col.mean()
    return t1

# 填充每一行的均值
def fill_nan_in_mean(t):
    for i in range(t.shape[0]):
        col = t[i]
        # 找出每一行是否存在nan
        nan_num = np.count_nonzero(col != col)
        if nan_num>0:
            col_not_nan = col[col == col]
            col[col != col] = np.mean(col_not_nan)





if __name__ == '__main__':
    t1 = np.arange(12).reshape((3, 4)).astype('float')

    # 将第二行,3,4列替换为nan
    t1[1, 2:] = np.nan
    print(t1)
    # print(t1)
    # [[  0.   1.   2.   3.]
    #  [  4.   5.  nan  nan]
    #  [  8.   9.  10.  11.]]
    # t1 = fill_nan(t1)
    fill_nan_in_mean(t1)
    print(t1)

